<template>
  <div
    class="file-list-container"
    @contextmenu.prevent="handleBlankRightClick"
    @click="clickFileList"
  >
    <!-- 文件列表展示 -->
    <div class="file-list-container">
      <!-- 文件列表 -->
      <el-row :gutter="20" class="file-list-row">
        <el-row v-if="fileList.length > 0">
          <el-col
            v-for="item in fileList"
            :key="item.id"
            :span="cardSpan"
            @dblclick.native="handleFolderDblClick(item)"
          >
            {{ item.fType }}
            <el-card
              class="file-card"
              @contextmenu.native.prevent="handleItemRightClick($event, item)"
            >
              <div>
                <img
                  :src="getFileTypeIcon(item.type)"
                  class="file-icon"
                  :alt="`${item.type} icon`"
                />
                <div class="file-meta">
                  <span class="file-name">{{ item.label }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-empty v-else description="暂无数据呢"></el-empty>
      </el-row>
    </div>

    <!-- 右键菜单 -->
    <context-menu
      ref="contextMenu"
      @refresh-all="handleRefreshAll"
      @new-folder="handleNewFolder"
      @upload-file="handleUploadFile"
      @upload-folder="handleUploadFolder"
      @authorizeFile="handleAuthorizeFile"
      @authorize="handleAuthorize"
      @refresh="handleRefresh"
      @open="handleOpen"
      @edit="handleEdit"
      @delete-folder="handleDeleteFolder"
      @delete-file="handleDeleteFile"
      @rename-folder="handleRenameFolder"
      @rename-file="handleRenameFile"
      @version="handleVersion"
      @rename="handleRenameWithContext"
    />

    <!-- 新建文件夹弹框 -->
    <el-dialog
      title="新建文件夹"
      :visible.sync="newFolderDialogVisible"
      width="30%"
      @closed="resetForm"
    >
      <el-form :model="folderForm" :rules="rules" ref="folderForm">
        <el-form-item prop="name">
          <el-input
            v-model="folderForm.name"
            placeholder="请输入文件夹名称"
            clearable
            @keyup.enter.native="confirmNewFolder"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="newFolderDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="confirmNewFolder"
          >确认</el-button
        >
      </span>
    </el-dialog>

    <!-- 文件及文件夹重命名 -->
    <el-dialog
      title="重命名"
      :visible.sync="renameDialogVisible"
      width="30%"
      center
    >
      <el-input
        v-model="renameForm.newName"
        placeholder="请输入新名称"
        clearable
        @keyup.enter.native="confirmRename"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="renameDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRename">确认</el-button>
      </span>
    </el-dialog>

    <!-- 文件上传组件 -->
    <input
      type="file"
      ref="fileInput"
      style="display: none"
      @change="handleFileUpload"
      multiple
    />

    <!-- 文件夹上传组件 -->
    <input
      type="file"
      ref="folderInput"
      style="display: none"
      @change="handleFileUpload"
      webkitdirectory
      multiple
    />

    <!-- 调整位置弹框 -->
    <el-dialog
      title="调整位置"
      :visible.sync="moveDialogVisible"
      width="30%"
      center
    >
      <el-select v-model="selectedFolder" placeholder="请选择目标文件夹">
        <el-option
          v-for="folder in folders"
          :key="folder"
          :label="folder"
          :value="folder"
        />
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="moveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmMove">确定</el-button>
      </span>
    </el-dialog>

    <!-- 版本信息弹窗 -->
    <el-dialog
      title="版本信息"
      :visible.sync="versionDialogVisible"
      width="90%"
      center
    >
      <el-table :data="versionData" style="width: 100%" height="500">
        <el-table-column prop="version" label="版本号" width="120" />
        <el-table-column prop="submitter" label="提交者" width="120" />
        <el-table-column prop="mark" label="说明" />
        <el-table-column prop="createdTime" label="时间" width="180" />
        <el-table-column label="操作" width="270">
          <template #default="scope">
            <el-row>
              <el-col :span="6">
                <el-button size="small" @click="handlePreview(scope.row)"
                  >预览</el-button
                >
              </el-col>
              <el-col :span="6">
                <el-button size="small" @click="handleCompare(scope.row)"
                  >对比</el-button
                >
              </el-col>
              <el-col :span="6">
                <el-button
                  size="small"
                  type="primary"
                  @click="handleUseVersion(scope.row)"
                >
                  使用此版本
                </el-button>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 文件预览 -->
    <FilePreview
      v-if="showPreview"
      :visible="showPreview"
      :file-url="previewUrl"
      :file-type="previewType"
      :file-content="previewContent"
      @close="closePreview"
    />
    <!-- 对比弹窗组件 -->
    <DiffModal :visible="showModal" @close="showModal = false" />

    <!-- 新增上传确认弹框 -->
    <el-dialog
      title="上传确认"
      :visible.sync="uploadDialogVisible"
      width="30%"
      center
      class="upload-confirm-dialog"
    >
      <!-- 文件列表 -->
      <div class="upload-files-list">
        <div
          v-for="(file, index) in selectedFiles"
          :key="index"
          class="file-item"
        >
          <i :class="getFileIcon(getFileType(file.name))"></i>
          <span class="file-name">{{ file.name }}</span>
        </div>
        <div v-if="selectedFiles.length > 3" class="more-files">
          等{{ selectedFiles.length }}个文件
        </div>
      </div>

      <!-- 密级选择 -->
      <el-select
        v-model="selectedLevel"
        placeholder="请选择密级"
        @change="handleLevelChange"
        clearable
      >
        <el-option
          v-for="item in securityLevels"
          :key="item.security"
          :label="item.securityValues"
          :value="item.security"
          :disabled="item.security > currentUserSecurity"
        >
        </el-option>
      </el-select>

      <!-- 文件名冲突处理 -->
      <div v-if="conflictFiles.length > 0" class="conflict-handle">
        <p>检测到同名文件 {{ conflictFiles[0].name }}</p>
        <el-radio-group v-model="handleType">
          <el-radio label="overwrite">覆盖</el-radio>
          <el-radio label="rename">重命名</el-radio>
        </el-radio-group>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUpload">取消</el-button>
        <el-button type="primary" @click="doUpload" :loading="uploading">
          {{ uploading ? "上传中..." : "开始上传" }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { checkPremission } from "@/api/zhishiku/permission";
import DiffModal from "./DiffModal.vue";
import FilePreview from "./FilePreview.vue";
import ContextMenu from "./ConMenu.vue";
import { getToken } from "@/utils/auth";
// import { renameFile } from "@/api/zhishiku/knowledge";
import { getfileList } from "@/api/zhishiku/fileVersion";
import { deleteFolder, renameFolder } from "@/api/zhishiku/folder";
import { deleteFile, renameFile } from "@/api/zhishiku/files";

export default {
  components: {
    ContextMenu,
    FilePreview,
    DiffModal,
  },
  props: {
    selectedNode: {
      pageNum: 1,
      pageSize: 10,
      userName: undefined,
      phonenumber: undefined,
      status: undefined,
      fileId: undefined,
      parentId: undefined,
    },
    folderTree: {
      // 接收树形数据
      type: Array,
      default: () => [],
    },
    fileList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      currentFiles: [],

      store: this.$store,

      submitting: false,
      folderForm: {
        name: "",
        parentId: 0, // 从当前目录上下文获取
      },
      rules: {
        name: [
          { required: true, message: "文件夹名称不能为空", trigger: "blur" },
          {
            pattern: /^[^/\\:*?"<>|]+$/,
            message: '名称不能包含 / \\ : * ? " < > | 等字符',
          },
        ],
      },

      selType: [],
      // 文件上传
      uploadDialogVisible: false,

      selectedLevel: null,
      securityLevels: [],
      currentUserSecurity: 0,

      handleType: "rename",
      conflictFiles: [],
      uploading: false,
      currentFolderId: 0, // 初始化为根目录

      securityOptions: [
        { value: 0, label: "普通" },
        { value: 1, label: "秘密" },
        { value: 2, label: "机密" },
        { value: 3, label: "绝密" },
      ],

      securityTypeMap: ["", "success", "warning", "danger"],
      securityLabelMap: ["普通", "秘密", "机密", "绝密"],

      renameDialogVisible: false,
      renameForm: {
        id: null,
        newName: "",
        type: null, // 'file' 或 'folder'
      },

      documentUrl: "",
      documentType: "docx",
      filesList: [],

      hoverIndex: -1,
      cardSpan: 6,
      showUpload: false,
      uploadDialogVisible: false,
      uploadFileName: "",
      uploadFile: null,
      moveDialogVisible: false,
      selectedFolder: "",
      folders: ["文件夹1", "文件夹2"],
      selectedFile: null,
      newFolderDialogVisible: false, // 新建文件夹弹框是否显示
      folderName: "", // 文件夹名称
      versionDialogVisible: false, // 版本信息弹窗是否显示
      versionData: [
        {
          version: "v1.0.0",
          submitter: "张三",
          description: "初始版本",
          time: "2023-10-01 12:00",
        },
      ], // 版本数据
      //文件预览数据
      showPreview: false,
      previewUrl: "",
      previewType: "",
      previewContent: "",
      //对比工具
      showModal: false,
      isDialogVisible: false, // 控制弹框显示
      permissionFileId: 0,
      //上传文件弹框参数
      selectedFiles: [], // 存储选中的文件
      permissionOptions: [
        // 权限选项
        { value: 0, label: "普通" },
        { value: 1, label: "秘密" },
        { value: 2, label: "机密" },
        { value: 3, label: "绝密" },
      ],
      selectedPermission: 0, // 选中的权限
      permission: false, //当前对象操作权限

      iconMap: {
        folder: require("@/assets/images/文件夹.png"),
        // word: require('@/assets/images/doc-iFcon.png'),
        file: require("@/assets/images/文件.png"),
        pdf: require("@/assets/images/文件.png"),
        doc: require("@/assets/images/文件.png"),

        // excel: require('@/assets/images/xls-icon.png'),
        // zip: require('@/assets/images/zip-icon.png'),
        // image: require('@/assets/images/image-icon.png'), // 新增
        // video: require('@/assets/images/video-icon.png'), // 新增
        default: require("@/assets/images/文件.png"),
      },
    };
  },
  watch: {
    fileList: {
      immediate: true,
      handler(newVal) {
        this.filesList = [...newVal]; // 创建新数组保证响应性
      },
    },
    "selectedNode.parentId": {
      immediate: true,
      handler(newParentId) {
        this.currentFolderId = newParentId || 0;
      },
    },
  },
  mounted() {
    this.loadSecurityLevels();

    // 获取当前选中的文件夹ID
    this.currentFolderId = this.selectedNode?.id || 0;

    this.checkSecurityLevels();

    // window.addEventListener("wheel", this.handleWheel);
    window.addEventListener("dragover", this.handleDragOver);
    window.addEventListener("dragleave", this.handleDragLeave);
    window.addEventListener("drop", this.handleDrop);
  },
  beforeDestroy() {
    // window.removeEventListener("wheel", this.handleWheel);
    window.removeEventListener("dragover", this.handleDragOver);
    window.removeEventListener("dragleave", this.handleDragLeave);
    window.removeEventListener("drop", this.handleDrop);
  },

  computed: {
    allowedSecurityLevels: {
      get() {
        return this.securityOptions.filter(
          (opt) => opt.value <= this.currentUserSecurity
        );
      },
      set(newVal) {
        // 可选的赋值逻辑（若需要响应式更新）
        this.$emit("update:security", newVal);
      },
    },
  },

  methods: {
    resetForm() {
      if (this.$refs.folderForm) {
        // 新增判断
        this.$refs.folderForm.resetFields();
      }
    },
    handleLevelChange(value) {
      console.log("选中密级:", value);
      this.selectedSecurity = value;
    },
    async loadSecurityLevels() {
      try {
        const token = getToken();
        const res = await this.$axios.get(
          `${process.env.VUE_APP_BASE_API}/api/files/levels`,
          {
            headers: { Authorization: `Bearer ${token}` },
          }
        );
        console.log("获取密级成功:", res.data);
        this.securityLevels = res.data.map((item) => ({
          security: item.security,
          securityValues: item.securityValues,
        }));
        // 设置默认选中当前用户密级
        this.currentUserSecurity = this.$store.state.user.security;
      } catch (error) {
        console.error("获取密级失败:", error);
        this.$message.error("密级加载失败");
      }
    },

    async checkSecurityLevels() {
      // 生成允许选择的密级选项
      this.allowedSecurityLevels = this.securityOptions.filter(
        (opt) => opt.value <= this.userSecurity
      );
    },

    // 执行上传
    async doUpload() {
      this.uploading = true;
      console.log("当前文件夹ID:", this.currentFolderId);
      try {
        const token = getToken();
        const formData = new FormData();

        this.selectedFiles.forEach((file, index) => {
          formData.append(`files`, file);
        });
        const dto = {
          folderId: this.currentFolderId,
          security: this.selectedSecurity,
          handleType: this.handleType,
        };
        formData.append(
          "dto",
          new Blob([JSON.stringify(dto)], { type: "application/json" })
        );
        const res = await this.$axios.post(
          // 服务器地址
          // "http://10.105.0.26:8080/api/files/uploadNew",

          // 本地地址
          "http://localhost:8080/api/files/uploadNew",
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
              Authorization: `Bearer ${token}`,
              "X-Custom-Header": "vue-upload",
            },
          }
        );

        if (res.data.code === 200) {
          this.$message.success("文件上传成功");
          this.$emit("refresh");
          this.resetUploadState();
        }
      } catch (error) {
        console.error("上传失败详情：", error.response);
        this.$message.error(
          `上传失败：${error.response?.data?.msg || "服务器错误"}`
        );
        this.handleUploadError(error);
      } finally {
        this.uploading = false;
      }
    },

    handleItemClick(item) {
      console.log(this.fileList);
      // 处理点击逻辑
      if (item.type === "folder") {
        this.$emit("selectFolder", item.id);
      } else {
        this.$emit("edit-event", item);
      }
    },
    // 双击文件夹处理
    async handleFolderDblClick(item) {
      try {
        if (item.type !== "folder") return;

        this.$emit("folder-change", { id: item.id });

        // 添加加载状态
        this.loading = true;

        const token = getToken();
        const res = await this.$axios.get(
          `${process.env.VUE_APP_BASE_API}/api/folder/${item.id}/contents`,
          { headers: { Authorization: `Bearer ${token}` } }
        );

        const responseData = res.data.data || {};
        // console.log("文件夹内容:", responseData);
        const subFolders = (responseData.childFolders || []).map((f) => ({
          id: f.id,
          parentId: f.parentId,
          label: f.name,
          type: "folder",
          security: f.security || 0,
          children: [],
        }));
        // console.log("subFolders", subFolders);

        const fileItems = (responseData.files || []).map((f) => ({
          id: f.id,
          label: f.name,
          type: "file",
          security: f.security || 0,
          currentVersion: f.currentVersion || 1,
          filePath: f.filePath, // 文件路径
        }));

        // 响应式更新数据
        this.currentFiles = JSON.parse(
          JSON.stringify([...subFolders, ...fileItems])
        );

        this.$emit("update-filelist", this.currentFiles);
      } catch (error) {
        console.error("文件夹内容加载失败:", error);
        console.error("加载失败:", error);
        this.$message.error(
          `错误: ${error.response?.data?.message || "网络异常"}`
        );
      } finally {
        this.loading = false;
      }
    },

    // 获取文件夹路径链
    getFolderPath(folderId) {
      const path = [];
      let currentNode = this.findNode(this.folderTree, folderId);
      while (currentNode) {
        path.unshift({ id: currentNode.id, name: currentNode.name });
        currentNode = this.findNode(this.folderTree, currentNode.parentId);
      }
      return path;
    },

    getFileTypeIcon(fileType) {
      const typeMap = {
        // 文件夹类型
        folder: "folder",

        // 文档类型
        doc: "doc",
        docx: "doc",

        // 表格类型
        xls: "xls",
        xlsx: "xls",

        // 图片类型
        jpg: "image",
        png: "image",

        // 视频类型
        mp4: "video",
        mov: "video",
      };

      return this.iconMap[typeMap[fileType]] || this.iconMap.default;
    },

    handleRenameWithContext({ contextType, file }) {
      // console.log("操作类型:", contextType);
      // console.log("文件对象:", file);
      this.handleRename(file);
    },
    async confirmRename() {
      if (!this.renameForm.newName) {
        this.$message.warning("名称不能为空");
        return;
      }

      try {
        let res;
        if (this.renameForm.type === "file") {
          // 调用文件重命名API
          res = await renameFile({
            fileId: this.renameForm.id,
            newName: this.renameForm.newName,
          });
        } else {
          // 调用文件夹重命名API
          res = await renameFolder({
            folderId: this.renameForm.id,
            newName: this.renameForm.newName,
          });
        }

        if (res.code === 200) {
          this.$message.success("重命名成功");

          // 刷新文件列表
          this.$emit("refresh-event");

          // 如果是文件夹重命名，还需要刷新树形结构
          if (this.renameForm.type === "folder") {
            this.$emit("refresh-tree");
          }

          this.renameDialogVisible = false;
        } else {
          this.$message.error(res.msg || "重命名失败");
        }
      } catch (error) {
        console.error("重命名失败", error);
        this.$message.error("重命名失败");
      }
    },

    // 重命名文件
    async handleRenameFile(file) {
      console.log("文件重命名", file);
      // 获取当前文件/文件夹的权限类型（0-文件，1-文件夹）
      const refType = this.selectedFile.type === "folder" ? 1 : 0;
      // 调用权限校验接口
      const hasPermission = await this.checkPermission(
        refType,
        this.selectedFile.id,
        "can_edit" // 操作类型需与后端约定（如view/read）
      );

      if (!hasPermission) {
        this.$message.error("无重命名权限");
        return;
      }
      this.renameForm = {
        id: this.selectedFile.id,
        newName: this.selectedFile.label,
        type: "file",
      };
      console.log("文件重命名renameForm:", this.renameForm);
      this.renameDialogVisible = true;
    },

    // 重命名文件
    async handleRenameFolder(file) {
      console.log("文件夹重命名", file);
      // 获取当前文件/文件夹的权限类型（0-文件，1-文件夹）
      const refType = this.selectedFile.type === "folder" ? 1 : 0;
      // 调用权限校验接口
      const hasPermission = await this.checkPermission(
        refType,
        this.selectedFile.id,
        "can_edit" // 操作类型需与后端约定（如view/read）
      );

      if (!hasPermission) {
        this.$message.error("无重命名权限");
        return;
      }
      this.renameForm = {
        id: this.selectedFile.id,
        newName: this.selectedFile.label,
        type: "folder",
      };
      console.log("文件夹重命名renameForm:", this.renameForm);
      this.renameDialogVisible = true;
    },

    // 设置权限对象
    setPermissionFileId(data) {
      this.permissionFileId = data;
    },
    // 打开弹框
    openDialog() {
      this.isDialogVisible = true;
    },
    // 处理确认操作
    handleConfirm(result) {
      this.isDialogVisible = false;
    },
    // 处理关闭操作
    handleClose() {
      this.isDialogVisible = false;
    },
    //预览方法
    closePreview() {
      this.showPreview = false;
    },
    getFileType(fileName) {
      const extension = fileName.split(".").pop().toLowerCase();
      switch (extension) {
        case "jpg":
        case "png":
        case "gif":
        case "bmp":
        case "webp":
          return "image";
        case "mp4":
        case "mov":
        case "avi":
        case "mkv":
          return "video";
        case "docx":
          return "docx";
        case "xlsx":
          return "xlsx";
        case "ppt":
        case "pptx":
          return "ppt";
        case "pdf":
          return "pdf";
        case "txt":
          return "text";
        default:
          return "unsupported";
      }
    },
    async checkPermission(refType, refId, action) {
      try {
        const currentUser = this.$store.state.user;
        // 管理员绕过校验
        if (currentUser?.isAdmin) return true;

        // 构造请求参数
        const params = {
          refType: refType, // 0-文件 1-文件夹
          refId: refId,
          action: action.toLowerCase(),
        };

        // 调用后端接口
        const res = await checkPremission(params);
        return res.data === true;
      } catch (error) {
        console.error("权限校验失败:", error);
        return false;
      }
    },

    clickFileList() {
      if (this.$refs.contextMenu) {
        this.$refs.contextMenu.hide();
      }
    },
    // 点击卡片
    clickCard(file) {
      // console.log("点击卡片");
      if (file.type === 1) {
        this.$emit("selectFloder", { id: file.id }); //触发侧边栏点击事件
      }
    },

    // 处理文件/文件夹右键点击
    handleItemRightClick(event, item) {
      event.stopPropagation(); // 阻止冒泡
      const contextType = item.type === "folder" ? "folder" : "file";

      this.selectedFile = item;
      // console.log("右键----------",this.selectedFile)

      console.log(item.type);
      this.$refs.contextMenu.show(event.clientX, event.clientY, contextType);
    },
    

    handleBlankRightClick(event) {
      console.log("空白");
      this.$refs.contextMenu.show(event.clientX, event.clientY, null);
    },

    handleMove() {
      this.moveDialogVisible = true;
    },
    handleUpload() {
      this.showUpload = true;
    },
    confirmMove() {
      console.log(
        `将文件 ${this.selectedFile.name} 移动到 ${this.selectedFolder}`
      );
      this.moveDialogVisible = false;
    },
    getCardClass(type) {
      return {
        "folder-card": type === "folder",
        "doc-card": ["doc", "docx"].includes(type),
        "media-card": ["mp4", "avi"].includes(type),
        "image-card": ["jpg", "png"].includes(type),
      };
    },
    // 获取文件图标
    getFileIcon(filename) {
      const ext = filename.split(".").pop().toLowerCase();
      const iconMap = {
        pdf: "el-icon-document",
        doc: "el-icon-document",
        docx: "el-icon-document",
        xls: "el-icon-s-data",
        xlsx: "el-icon-s-data",
        // 添加更多文件类型映射...
      };
      return iconMap[ext] || "el-icon-document";
    },

    handleDragOver(event) {
      event.preventDefault(); // 阻止默认行为
      if (!this.showUpload) {
        this.showUpload = true; // 只有当文件拖入时才显示上传组件
      }
    },
    handleDragLeave(event) {
      // 判断鼠标是否真正离开了拖拽区域
      if (!event.relatedTarget || !this.$el.contains(event.relatedTarget)) {
        this.showUpload = false; // 只有当鼠标离开整个拖拽区域时才隐藏上传组件
      }
    },
    handleDrop(event) {
      event.preventDefault(); // 阻止默认行为
      this.showUpload = false; // 隐藏上传组件

      const files = event.dataTransfer.files; // 获取拖拽的文件
      if (files.length > 0) {
        this.uploadFile = files[0]; // 保存文件对象
        this.uploadFileName = files[0].name; // 保存文件名
        this.uploadDialogVisible = true; // 显示上传确认弹框
      }
    },
    handleBeforeUpload(file) {
      // 文件上传前的校验
      const isImage = file.type === "image/jpeg" || file.type === "image/png";
      const isLt500KB = file.size / 1024 < 500;

      if (!isImage) {
        this.$message.error("只能上传jpg/png文件！");
      }
      if (!isLt500KB) {
        this.$message.error("文件大小不能超过500KB！");
      }
      return isImage && isLt500KB;
    },
    handleUploadSuccess(response, file) {
      // 上传成功后的处理
      this.$message.success("文件上传成功！");
      this.fileList.push({ name: file.name, type: "file" }); // 将上传的文件添加到文件列表
    },
    handleUploadError(error) {
      if (error.response) {
        const { status, data } = error.response;
        switch (status) {
          case 409:
            this.conflictFiles = data.conflictFiles;
            this.$message.warning("检测到新的文件冲突，请重新选择处理方式");
            break;
          case 403:
            this.$message.error("您没有权限在此目录上传文件");
            break;
          default:
            this.$message.error(`上传失败: ${data.message || "服务器错误"}`);
        }
      } else {
        this.$message.error("网络错误，请检查连接");
      }
    },
    // 取消上传
    cancelUpload() {
      this.resetUploadState();
      this.$message.info("已取消上传");
    },
    // 重置上传状态
    resetUploadState() {
      this.uploadDialogVisible = false;
      this.selectedFiles = [];
      this.conflictFiles = [];
      this.selectedSecurity = 0;
      this.handleType = "rename";
      this.$refs.fileInput.value = null;
    },

    // 处理文件/文件夹上传
    handleFileUpload(event) {
      const files = Array.from(event.target.files).filter(
        (file) => !file.name.startsWith("~$")
      ); // 过滤以 ~$ 开头的文件

      if (files.length > 0) {
        this.selectedFiles = files;
        this.uploadDialogVisible = true;
      }
      event.target.value = ""; // 清空选择
    },

    async handleNewFolder() {
      // 获取当前文件夹信息
      const currentFolder = this.folderTree.find(
        (f) => f.id === this.currentFolderId
      );

      // 2. 校验操作权限
      const hasPermission = await this.checkPermission(
        1,
        this.currentFolderId,
        "can_add"
      );
      // console.log("hasPermission:", hasPermission);
      if (!hasPermission) {
        this.$message.error("无新建文件夹权限");
        return;
      }

      this.newFolderDialogVisible = true;
    },

    // 确认新建文件夹
    async confirmNewFolder() {
      try {
        const token = getToken();
        await this.$refs.folderForm.validate();
        this.submitting = true;

        const response = await this.$axios.post(
          `${process.env.VUE_APP_BASE_API}/api/folder/createFolder`,
          {
            name: this.folderForm.name,
            parentId: this.currentFolderId,
            security: 0, // 默认普通密级
          },
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        );

        if (response.data.code === 200) {
          //刷新
          this.$emit("refresh-event");

          this.$message.success("创建成功");

          this.newFolderDialogVisible = false;
        }
      } catch (error) {
        if (
          error.response &&
          error.response.data &&
          error.response.data.msg &&
          error.response.data.msg.includes("同名")
        ) {
          this.$message.error(
            `文件夹名称 "${this.folderForm.name}" 已存在，请使用其他名称`
          );
        }
      } finally {
        this.submitting = false;
      }
    },

    validateFolderName() {
      const regex = /^[^\s\/\\:*?"<>|]+$/;
      if (!regex.test(this.folderName)) {
        this.$message.error("名称包含非法字符");
        return false;
      }
      return true;
    },

    async handleUploadFile() {
      // 获取当前文件夹信息
      const currentFolder = this.folderTree.find(
        (f) => f.id === this.currentFolderId
      );

      // console.log("this.currentFolderId:", this.currentFolderId);

      // 2. 校验操作权限
      const hasPermission = await this.checkPermission(
        1,
        this.currentFolderId,
        "can_add"
      );
      console.log("hasPermission:", hasPermission);
      if (!hasPermission) {
        this.$message.error("无上传权限");
        return;
      }

      // 使用当前所在的文件夹ID
      this.$refs.fileInput.click();
    },
    // 文件选择后处理
    async onFileSelected(e) {
      const files = Array.from(e.target.files);
      if (!files.length) return;

      this.selectedFiles = files;
      this.uploadDialogVisible = true;

      // 检查文件冲突
      // await this.checkFileConflicts();
    },
    // 检查文件名冲突
    // async checkFileConflicts() {
    //   try {
    //     const res = await this.$axios.post("/api/files/check-conflict", {
    //       folderId: this.currentFolderId,
    //       filenames: this.selectedFiles.map((f) => f.name),
    //     });

    //     this.conflictFiles = res.data.conflictFiles;
    //   } catch (error) {
    //     console.error("文件冲突检查失败:", error);
    //     this.conflictFiles = [];
    //   }
    // },

    async handleUploadFolder() {
      console.log("上传文件夹");
      // //判断权限
      // const permission = await this.checkPremiss(3);
      // if (permission) {
      //   this.$refs.folderInput.click(); // 触发文件夹选择
      // } else {
      //   this.$message.error("您没有权限上传文件夹");
      // }
    },
    handleAuthorize() {
      //文件夹
      console.log("授权");
      this.setPermissionFileId(this.selectedNode.parentId);
      this.isDialogVisible = true;
    },
    handleAuthorizeFile() {
      //文件
      console.log("授权");
      this.setPermissionFileId(this.selectedFile.id);
      this.isDialogVisible = true;
    },

    handleRefresh() {
      console.log("刷新文件列表");
      this.$emit("refresh-event");
      this.$message.success("刷新成功");
    },
    // 处理全部刷新事件
    handleRefreshAll() {
      console.log("触发全部刷新");
      // 先刷新文件列表
      this.handleRefresh();

      // 然后触发刷新树形组件的事件
      this.$emit("refresh-tree");
    },

    async handleOpen() {
      // 调用权限校验接口
      const hasPermission = await this.checkPermission(
        0,
        this.selectedFile.id,
        "can_view"
      );

      if (!hasPermission) {
        this.$message.error("无查看权限");
        return;
      }

      this.$emit("edit-event", this.selectedFile);
      console.log("查看：", this.selectedFile);
    },

    async handleEdit() {
      // 获取当前文件/文件夹的权限类型（0-文件，1-文件夹）
      const refType = this.selectedFile.type === "folder" ? 1 : 0;

      // 调用权限校验接口
      const hasPermission = await this.checkPermission(
        refType,
        this.selectedFile.id,
        "can_edit"
      );

      if (!hasPermission) {
        this.$message.error("无编辑权限");
        return;
      }
      this.$emit("edit-event", this.selectedFile);
    },
    async handleDeleteFile() {
      console.log("删除文件");

      // 检查权限
      const hasPermission = await this.checkPermission(
        0, // 文件类型
        this.selectedFile.id, // 文件ID
        "can_delete" // 操作类型
      );
      if (!hasPermission) {
        this.$message.error("无删除权限");
        return;
      }

      if (!this.selectedFile) {
        this.$message.warning("请选择要删除的文件");
        return;
      }

      try {
        // 二次确认
        await this.$confirm(
          `确定要删除文件 "${this.selectedFile.label}" 吗？`,
          "删除确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        // 调用删除API
        const res = await deleteFile(this.selectedFile.id);
        if (res.code === 200) {
          this.$message.success("文件删除成功");
          // 刷新文件列表
          this.$emit("refresh-event");
        } else {
          this.$message.error(res.msg || "删除失败");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除文件失败:", error);
          this.$message.error("删除文件失败");
        }
      }
    },
    async handleDeleteFolder() {
      console.log("删除文件夹");
      // 检查权限
      const hasPermission = await this.checkPermission(
        1, // 文件夹类型
        this.selectedFile.id, // 文件夹ID
        "can_delete" // 操作类型
      );
      if (!hasPermission) {
        this.$message.error("无删除权限");
        return;
      }

      if (!this.selectedFile) {
        this.$message.warning("请选择要删除的文件夹");
        return;
      }

      try {
        // 二次确认 - 警告文件夹删除会连带删除所有内容
        await this.$confirm(
          `确定要删除文件夹 "${this.selectedFile.label}" 吗？<br><strong style="color: red;">此操作将删除该文件夹及其所有子文件夹和文件！</strong>`,
          "删除确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            dangerouslyUseHTMLString: true,
          }
        );
        console.log("删除文件夹: ", this.selectedFile);
        console.log("999删除文件: ", this.currentFiles.id);

        // 调用删除API
        const res = await deleteFolder(this.selectedFile.id);

        if (res.code === 200) {
          this.$message.success("文件夹删除成功");
          // 刷新文件列表和文件夹树
          this.$emit("refresh-event");
          this.$emit("refresh-tree");
        } else {
          this.$message.error(res.msg || "删除失败");
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除文件夹失败:", error);
          this.$message.error("删除文件夹失败");
        }
      }
    },

    handleVersion() {
      console.log("版本");
      let formData = new FormData();
      formData.append("fileId", this.selectedFile.id);
      // 调用后端接口上传文件
      getfileList(formData).then((response) => {
        this.versionData = response.rows;
        // console.log(response);
      });
      this.versionDialogVisible = true;
    },
    // 预览版本
    handlePreview(row) {
      // console.log("预览版本:", row.version);
      this.$message.success(`预览版本 ${row.version}`);
    },
    // 对比版本
    handleCompare(row) {
      // console.log("对比版本:", row.version);
      this.$message.success(`对比版本 ${row.version}`);
      this.showModal = true;
    },
    // 使用此版本
    handleUseVersion(row) {
      console.log("使用此版本:", row.version);
      this.$message.success(`已切换到版本 ${row.version}`);
    },
  },
};
</script>

<style scoped>
.file-list-container {
  min-width: 1000px;
  max-width: 100%;
  width: fit-content;
  overflow: hidden;
}

.file-card {
  background-color: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

.file-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100px;
}

.file-icon {
  width: 45px;
  /* 根据实际图片尺寸调整 */
  height: 45px;
  object-fit: contain;
  margin-bottom: 8px;
}

.file-content i {
  display: none;
}

.file-content span {
  font-size: 14px;
  color: #333;
}

/* 文件夹 */
.folder-card .file-content i {
  background-color: #f0f9eb;
  color: #67c23a;
}

/* 图片 */
.image-card .file-content i {
  background-color: #fff0f6;
  color: #f56c6c;
}

/* 视频 */
.video-card .file-content i {
  background-color: #f0f4ff;
  color: #409eff;
}

/* 文档 */
.document-card .file-content i {
  background-color: #f4f4f5;
  color: #909399;
}

/* 音频 */
.audio-card .file-content i {
  background-color: #f0f9eb;
  color: #67c23a;
}

/* 压缩文件 */
.archive-card .file-content i {
  background-color: #fdf6ec;
  color: #e6a23c;
}

/* 代码文件 */
.code-card .file-content i {
  background-color: #f0f4ff;
  color: #409eff;
}

/* 其他 */
.other-card .file-content i {
  background-color: #f4f4f5;
  color: #909399;
}

.file-content i:hover {
  opacity: 0.7;
  filter: brightness(0.6);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
  /*  加上阴影效果 */
}

.file-content i {
  font-size: 300%;
  /* 根据卡片大小调整 */
}

.file-content span {
  font-weight: bold;
  color: #333;
}

/* 自定义版本弹窗样式 */
.el-dialog__header {
  background-color: #f5f7fa;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.el-dialog__title {
  font-size: 18px;
  font-weight: bold;
}

.el-table {
  margin-top: 10px;
}

.el-button {
  margin-right: 5px;
}

.file-list-row {
  min-height: 500px;
  width: 100%;
}

/* 新增样式 */
.upload-confirm-dialog {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
}

.upload-files-list {
  max-height: 200px;
  overflow-y: auto;
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px;
  margin: 4px 0;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.file-item i {
  font-size: 20px;
  margin-right: 10px;
  color: #606266;
}

.file-name {
  font-size: 14px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.more-files {
  color: #909399;
  font-size: 12px;
  text-align: center;
  padding: 8px;
}

.permission-select {
  display: flex;
  align-items: center;
  margin-top: 15px;
}

.select-label {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.permission-dropdown {
  flex: 1;
}

.dialog-footer {
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.context-menu {
  z-index: 9999 !important;
  /* 强制置顶 */
  position: fixed;
}
</style>
